package com.startupwebapp.services.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.startupwebapp.core.domain.users.Person;
import com.startupwebapp.core.domain.users.PersonRole;
import com.startupwebapp.services.PersonService;

@Service("userDetailsService")
public class SpringUserDetailsServiceImp implements UserDetailsService {
	@Autowired
	private PersonService personService;
	private Person person = null;
	private UserDetails details = null;
	private GrantedAuthority[] authorities;

	public UserDetails loadUserByUsername(String login)
			throws UsernameNotFoundException, DataAccessException {

		findPersonByLogin(login);
		populateUserDelails();
		return details;
	}

	private void populateUserDelails() {
		if (person != null) {
			createAuthorities();
			createUserDetails();
		} else {
			error();

		}
	}

	private void error() {
		throw new UsernameNotFoundException("user not found in database");
	}

	private void createUserDetails() {

		details = new org.springframework.security.userdetails.User(person
				.getLogin(), person.getPasswordHash(), true, true, true, person
				.getActive(), authorities);
	}

	private void createAuthorities() {
		authorities = new GrantedAuthority[person.getRoles().size()];
		int i = 0;
		for (PersonRole role : person.getRoles()) {
			authorities[i++] = new GrantedAuthorityImpl(role
					.getPrefixedRoleName());
		}

	}

	private void findPersonByLogin(String login) {
		person = personService.findByLogin(login);
	}
}
